import Taro from '@tarojs/taro';
import { MaterialIcons } from 'taro-icons';
import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView } from '@tarojs/components';

import NineImage from '../../components/NineImage';
import PageHeader from '../../components/pageHeader';
import { useAppContext } from '../../contexts/AppContext';
import ProcessTitle from '../../components/processStep/processTitle';
import ProcessStatus from '../../components/processStep/processStatus';
import { CompleteButton, NextButton } from '../../components/processStep/processButton';
import { getUserProgressStepApi, setUserProgressStepStatusApi } from '../../api/myself';
import '../user-study-time/index.scss';

const UserSubjectAppointment: React.FC = () => {
  const firstLoadRef = useRef<boolean>(false);
  const [userStep, setUserStep] = useState<any>({
    id: 0,
    name: "",
    status: 0,
    completed_time: "",
    children: []
  });
  const stepId = Number(Taro.getCurrentInstance().router?.params?.stepId || '6');
  const [showTextContent, setShowTextContent] = useState('image');
  const subjectId = Number(Taro.getCurrentInstance().router?.params?.tab || '2');
  const { setCarSubjectStepProcessStatus } = useAppContext();

  // 获取初始化信息
  const getInitInfoData = async () => {
    try {
      const res = await getUserProgressStepApi(Number(stepId));
      if(res.code === 200 && res.data.length == 1) {
        const result = res.data[0];
        setUserStep({
          id: stepId,
          name: result.name,
          status: result.status,
          completed_time: result.created_at,
          children: result.children?.split(',') || [],
        });
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '获取用户进度失败', icon: 'none' });
    }
  }

  // 更新步骤状态
  const updateStepStatus = async () => {
    try {
      const res = await setUserProgressStepStatusApi(stepId, 1);
      if(res.code === 200) {
        setUserStep({
          ...userStep,
          status: 2
        });
        setCarSubjectStepProcessStatus(stepId, 1);
        Taro.showToast({ title: '已完成科目二约考~', icon: 'success' });
      }
    } catch(err) {
      console.log(err);
      Taro.showToast({ title: '操作失败，请稍后重试~', icon: 'none' });
    }
  }

  // 跳转到下一步
  const navigateToNextStep = () => {
    Taro.navigateTo({
      url: `/pages/user-progress/index?stepId=${Number(stepId) + 1}`
    });
  };

  useEffect(() => {
    if (!stepId) return;
    if (!firstLoadRef.current) {
      firstLoadRef.current = true;
      getInitInfoData();
    }
  }, [stepId]);

  return (
    <View className="page-container study-time-container">
      <PageHeader title={subjectId === 2 ? '科目二约考' : '科目三约考'} />
      {userStep.completed_time && (
        <ProcessStatus title={subjectId === 2 ? '科目二约考' : '科目三约考'} createTime={userStep.completed_time} />
      )}

      <View className="study-time-content-container">
        <View className="main-card">
          <Text className="steps-title"></Text>
          <ProcessTitle 
            content={subjectId === 2 ? ' 约考科目二' : ' 约考科目三'}
            showTextContent={showTextContent} 
            setShowTextContent={setShowTextContent} />
          <View className="study-time-steps">
            {showTextContent == 'text' && (
              <ScrollView scrollY>
                <View className="steps-list">
                  <View className="step-item">
                    <View className="step-time-number">1</View>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>打开<Text className="importance-text">交管12123APP</Text></View>
                        <View>点击<Text className="importance-text">更多</Text></View>
                        <View>找到<Text className="importance-text">考试预约</Text></View>
                      </View>
                    </View>
                  </View>

                  <View className="step-item">
                    <Text className="step-time-number">2</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>点击<Text className="importance-text">选择考场</Text></View>
                        <View>选择和教练沟通确定的考场</View>
                      </View>
                    </View>
                  </View>

                  <View className="step-item">
                    <Text className="step-time-number">3</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>点击<Text className="importance-text">选择时间</Text></View>
                        <View>选择第一场时间</View>
                        <View>选择第二场时间</View>
                        <View>要求两场都要选择，之后点击<Text className="importance-text">预约</Text>按钮</View>
                      </View>
                    </View>
                  </View>

                  <View className="step-item">
                    <Text className="step-time-number">4</Text>
                    <View className="step-content">
                      <View className="step-image-container">
                        <View>点击<Text className="importance-text">预约信息</Text></View>
                        <View>等待受理成功，短信通知预约成功</View>
                      </View>
                    </View>
                  </View>
                </View>
              </ScrollView>
            )}
            {showTextContent == 'image' && (
              <NineImage images={null} stepId={stepId} />
            )}

          </View>

          {/* 特别注意 */}
          <View className="study-time-notice">
            <View className="notice-title">
              <MaterialIcons name="info" size={20} color="#e6a23c" className="mr-2" />
              <Text className="notice-title-text text-lg">特别注意</Text>
            </View>
            <View className="notice-content">
              <View>
                <View className='text-md'>1、约考前请确保您已完成所有科目训练学时</View>
                <View className='text-md'>2、预约成功后，请按时参加考试，逾期将视为缺考</View>
                <View className='text-md'>3、考试当天请携带有效身份证、学员证等相关证件</View>
                <View className='text-md'>4、如遇特殊情况无法参加考试，请提前取消预约</View>
              </View>
            </View>
          </View>

          {/* 底部按钮 */}
          <View className="button-container">
            {userStep.status === 0 ? (
              <CompleteButton content='完 成 约 考' onClick={updateStepStatus}/>
            ) : (
              <NextButton onClick={navigateToNextStep}/>
            )}
          </View>
        </View>
      </View>
    </View>
  );
}

export default UserSubjectAppointment;